package com.mce.nebula.service;

import com.mce.nebula.entity.Team;
import com.mce.nebula.entity.User;
import com.mce.nebula.repository.TeamRepository;
import com.mce.nebula.util.ValidationUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.UUID;

/**
 * 团队服务
 * 对应Python的team_services
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class TeamService {
    
    private final TeamRepository teamRepository;
    
    /**
     * 创建团队
     */
    @Transactional
    public Team createTeam(User user, String enterpriseId, List<String> regions, 
                          String regionName, String teamName, String namespace) {
        
        Team team = new Team();
        team.setTenantId(UUID.randomUUID().toString().replace("-", ""));
        team.setTenantName(teamName);
        team.setTenantAlias(teamName);
        team.setNamespace(namespace);
        team.setCreater(user.getId());
        team.setEnterpriseId(enterpriseId);
        team.setIsActive(true);
        
        return teamRepository.save(team);
    }
    
    /**
     * 创建团队（简化版本）
     */
    @Transactional
    public Team createTeam(User user, String enterpriseId, String teamName) {
        // 规范化团队名称
        String normalizedName = ValidationUtils.normalizeNameForK8sNamespace(teamName);
        
        Team team = new Team();
        team.setTenantId(UUID.randomUUID().toString().replace("-", ""));
        team.setTenantName(normalizedName);
        team.setTenantAlias(normalizedName);
        team.setNamespace(normalizedName);
        team.setCreater(user.getId());
        team.setEnterpriseId(enterpriseId);
        team.setIsActive(true);
        
        return teamRepository.save(team);
    }
    
    /**
     * 设置团队资源限制
     */
    @Transactional
    public void setTenantResourceLimit(String enterpriseId, String regionId, 
                                     String tenantName, ResourceLimit limit) {
        // 这里应该实现资源限制设置逻辑
        // 简化处理
        log.info("设置团队 {} 在区域 {} 的资源限制: CPU={}, Memory={}, Storage={}", 
                tenantName, regionId, limit.getLimitCpu(), limit.getLimitMemory(), limit.getLimitStorage());
    }
    
    /**
     * 资源限制类
     */
    public static class ResourceLimit {
        private int limitMemory; // MB
        private int limitCpu;    // mCPU
        private int limitStorage; // MB
        
        public ResourceLimit(int limitMemory, int limitCpu, int limitStorage) {
            this.limitMemory = limitMemory;
            this.limitCpu = limitCpu;
            this.limitStorage = limitStorage;
        }
        
        // Getters
        public int getLimitMemory() { return limitMemory; }
        public int getLimitCpu() { return limitCpu; }
        public int getLimitStorage() { return limitStorage; }
    }
}